import cgi
import database
from google.appengine.ext import db
from google.appengine.ext import webapp

class QueryDatabaseGUIMainHandler(webapp.RequestHandler):
	def print_query_form(self, gql_command):
		self.response.out.write("""
			<html><body>GQL Command:<br>
			<form action="/query_database_gui" method="post">
				<div><textarea name="gql_command" rows="3" cols="60">%s</textarea></div>
				<div><input type="submit" value="Query"></div>
			</form>
			</body></html>
		""" % gql_command)
		
	def post(self):
		self.print_query_form(cgi.escape(self.request.get("gql_command")))
		try:
			query_result = db.GqlQuery(cgi.escape(self.request.get("gql_command")))
			self.response.out.write("Result:" + str(query_result.count()) + "<br><table border=1>")
			is_header_printed = False
			for entry in query_result:
				# print header
				if not is_header_printed:
					self.response.out.write("<tr>")
					for member_var_key in entry.__dict__["_entity"].keys():
						self.response.out.write("<th>%s</th>" % str(member_var_key) )
					self.response.out.write("</tr>")
					is_header_printed = True

				# print data
				self.response.out.write("<tr>")
				for member_var_key in entry.__dict__["_entity"].keys():
					self.response.out.write("<td>")
					self.response.out.write(entry.__dict__["_entity"][member_var_key])
					self.response.out.write("</td>")
				self.response.out.write("</tr>")
			self.response.out.write("</table>")
		except db.BadQueryError:
			self.response.out.write("Wrong Query!")
		
	def get(self):
		self.print_query_form("")

		

